package two.chapter_1.c1_3;

import java.util.Iterator;

/**
 * 以栈为目标的队列
 *
 * 维护栈指针
 */
public class Steque<Item> implements Collection<Item>{

    private Node head;//栈顶同时也是队首
    private Node tail; //栈底同时也队尾
    private int size;
    /**
     * 入栈 需同时改变head，tail指针
     * @param item
     */
    public void push(Item item){
        Node node=new Node(item);
        if (isEmpty()){
            head=tail=node;
        }else {
            node.next=head;//栈方向
            head=node;


        }
        size++;
    }

    public Item pop(){
        if (isEmpty()){
            throw new CollectionEmptyException();
        }
        Item item=head.item;
        head=head.next;
        size--;
        return item;
    }
    /**
     * 入队列 从栈底入  需要同时更改head tail指针
     * @param item
     */
    public void enqueue(Item item){
        Node node=new Node(item);
        if (isEmpty()){
            head=tail=node;
        }else {
            tail.next=node;
            tail=node;

        }

        size++;
    }

    @Override
    public boolean isEmpty() {
        return size()==0;
    }

    @Override
    public int size() {
        return size;
    }

    @Override
    public Iterator<Item> iterator() {
        return new Iter();
    }

    private class Node{
        Item item;
        Node next;
        public Node(Item item){
            this.item=item;
        }
    }

    private class Iter implements Iterator<Item>{
        private Node next=head;
        private int count=size();
        @Override
        public boolean hasNext() {
            return count>0;
        }

        @Override
        public Item next() {
            count--;
            Item item=next.item;
            next=next.next;
            return item;
        }

        @Override
        public void remove() {

        }
    }
}
